package com.learning.netease.distributed.lock.zk.zklock;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * ClassName: ZkWatcherDemo
 * Description: 简单监听的demo
 * Date: 2019/3/20 13:54 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ZkWatcherDemo {


    /**
     * 创建持久节点
     */
    public void createNode() {
        ZkClient client = new ZkClient("localhost:2181");
        // 设置序列化器
        client.setZkSerializer(new MyZkSerializer());

        client.createPersistent("/demo");
    }

    /**
     * 临时有序节点
     * [0000000000]
     *
     * @throws InterruptedException
     */
    public void createSeqNode() throws InterruptedException {
        ZkClient client = new ZkClient("localhost:2181");
        // 设置序列化器
        client.setZkSerializer(new MyZkSerializer());

        client.createEphemeralSequential("/demo/", "lock");

        List<String> children = client.getChildren("/demo");

        System.out.println(children.toString());

    }

    /**
     * 监控
     *
     * @throws InterruptedException
     */
    public void addLintener() throws InterruptedException {

        ZkClient client = new ZkClient("localhost:2181");

        // 设置序列化器
        client.setZkSerializer(new MyZkSerializer());

        // 监听
        client.subscribeDataChanges("/demo", new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println("收到节点数据被修改了");
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("收到节点被删除了");
            }
        });


    }
}
